package heliotrope.net.loader
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	public class SoundLoader extends EventDispatcher implements ILoader
	{
		private var _loader:Sound;
		private var _url:URLRequest;
		private var _target:ILoadTarget;
		public function SoundLoader()
		{
		}
		public function load(url:String, target_:ILoadTarget, loadType:String=""):void
		{
			_url = new URLRequest(url);
			try
			{
				_loader = new Sound;
				addListeners()
				_loader.load(_url);
			}
			catch(error:Error)
			{
				trace("Can't load!" + error.message);
			}
			_target = target_;
		}
		
//		override public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
//		{
//			super.removeEventListener(type, listener, useCapture);
//			remove();
//		}
		
		protected function addListeners():void
		{
			_loader.addEventListener(Event.COMPLETE,completeHandler);
			_loader.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			_loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
		}
		
		
		protected function delListeners():void
		{
			if(!_loader)
				return;
			_loader.removeEventListener(Event.COMPLETE,completeHandler);
			_loader.removeEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			_loader.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
		}
		
		protected function completeHandler(event:Event):void
		{
			_target.saveData(_loader);
			dispatchEvent(event);
			//remove();
		}

		protected function progressHandler(event:ProgressEvent):void
		{
			dispatchEvent(event);
		}
		
		protected function ioErrorHandler(event:IOErrorEvent):void
		{
			//====the code below is necessary====
			try
			{
				_loader.close();
			}
			catch(error:Error)
			{
				trace("Loader closing error:"+error);
			}
			//====================================
			dispatchEvent(event);
			//trace(evt.type + " at " + this.toString() + _url.url);
			//Alert.show("读取文件出错，未找到文件！");
		}
		
		public function unload():void
		{
			remove();
		}
		protected function remove():void
		{
			delListeners();
			try
			{
				_loader.close();
			}
			catch(error:Error)
			{
				trace("Loader closing error:"+error);
			}
			_loader = null;
			_target = null;
		}
		
		public function get target():ILoadTarget
		{
			return _target;
		}
	}
}